package com.ruoyi.web.controller.tool.designpattern.structuralPatterns.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * 享元模式
 *
 * @author Hack2003
 * @date 2024/3/21 17:10
 **/
// 1. 定义享元对象的内部类
class Flyweight {
    private String state;

    public Flyweight(String state) {
        this.state = state;
    }

    public void operation() {
        // 具体的业务操作
        System.out.println("享元操作与状态: " + state);
    }
}

// 2. 定义享元工厂类
class FlyweightFactory {
    private Map<String, Flyweight> flyweights = new HashMap<>();

    public Flyweight getFlyweight(String state) {
        Flyweight flyweight = flyweights.get(state);
        if (flyweight == null) {
            flyweight = new Flyweight(state);
            flyweights.put(state, flyweight);
        }
        return flyweight;
    }
}

/**
 * 享元模式是一种结构型设计模式，(旨在通过共享对象来减少内存使用和提高性能。)
 * 它通过共享技术来有效地支持大量细粒度的对象，
 * 从而减少内存的使用。
 * 享元模式通常用于处理大量相似或重复对象的情况，
 * 通过重用已经存在的对象来降低系统的内存开销。
 */
public class Test {
    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();

        Flyweight flyweight1 = factory.getFlyweight("状态1");
        flyweight1.operation();

        Flyweight flyweight2 = factory.getFlyweight("状态2");
        flyweight2.operation();

        Flyweight flyweight3 = factory.getFlyweight("状态3");
        flyweight3.operation();

        // 输出结果：
        // Flyweight operation with state: state1
        // Flyweight operation with state: state2
        // Flyweight operation with state: state1
    }
}
